package com.knowif.backend.service;

import java.util.*;

import javax.servlet.ServletContext;

import com.knowif.dao.TUserMapper;
import com.knowif.dao.TopicMapper;
import com.knowif.util.WechatMiniUtil;
import com.knowif.util.commonUtil.SecurityUtil;
import com.knowif.util.paramUtil.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.knowif.dao.TutorInfoMapper;
import com.knowif.enumInfo.RefundTypeEnum;
import com.knowif.enumInfo.UserOrderStatusEnum;
import com.knowif.pojo.SettleParam;
import com.knowif.pojo.TUser;
import com.knowif.pojo.UserOrder;
import com.knowif.pojo.UserOrderFlow;
import com.knowif.pojo.UserWechat;
import com.knowif.service.SettleParam_service;
import com.knowif.service.UserPayOrder_service;
import com.knowif.service.UserWechat_service;
import com.knowif.service.User_service;
import com.knowif.system.model.RestBean;

@Service//订单状态 ： 1.未支付 2.已支付 3.失效订单 4.导师接单 5.已交易 6.取消订单 7.退款订单 8. 待评价
public class UserOrderHandleService {
    @Autowired
    private UserPayOrder_service userPayOrderService;
    @Autowired
    private UserOrderFlowService userOrderFlowService;
    @Value("${wechat.config.constant.refundNotifyUrl}")
    private  String refundNotifyUrl;
    @Autowired
    private User_service user_service;
    @Autowired
    private SettleParam_service settleParam_service;
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private WechatMiniUtil wechatMiniUtil;
    @Autowired
    private UserWechat_service userWechat_service;
    @Autowired
    private TutorInfoMapper tutorInfoMapper;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private TopicMapper topicMapper;


    /**
     * 用户下单
     * */
    public RestBean<?> userConfirmOrder(UserOrder userOrder){
        userOrder.setStatus(1);
        userPayOrderService.insertOrder(userOrder);
        if(userOrder.getId() == 0){
            return RestBean.buildError();
        }else{
            return RestBean.buildSuccess(userOrder.getId());
        }
    }


    /**
     * 导师接单
     * */
    public RestBean<?> teacherAcceptOrder(int userOrderId,String openid){
        UserOrder userOrder = userPayOrderService.selectUserOrderById(userOrderId);
        Integer toUserId = userOrder.getToUserId();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(toUserId);
        List<TUser> users = user_service.selectByUserIds(ids);
        if(users == null || users.isEmpty()){
            return RestBean.build(RestBean.not_authorized,"当前人员无法进行此操作");
        }
        if(!users.get(0).getOpenid().equals(openid)){
            return RestBean.build(RestBean.not_authorized,"当前人员无法进行此操作");
        }
        if(userOrder.getStatus() == 2){
            userOrder.setStatus(4);
            userPayOrderService.updateOrder(userOrder);
            TUser user = tUserMapper.selectByPrimaryKey(userOrder.getUserId());
            TUser toUser = tUserMapper.selectByPrimaryKey(userOrder.getToUserId());
            if(user != null){
                String accessToken = (String) servletContext.getAttribute("wechatAccessToken");
                UserWechat userWechat = userWechat_service.selectByMiniOpenid(user.getOpenid());
                UserWechat userWechat1 = userWechat_service.selectByMiniOpenid(toUser.getOpenid());
                // uxEAjSnPqNtAOsFBCZVsGAWs1gedv166LvJM4jX--2w (即导师在订单详情页操作“接受”订单  学员 导师)
                List<Map<String,String>> maps = new LinkedList<>();
                String value1 = SecurityUtil.stringToMD5(userOrder.getId()+"");
                String value2 = toUser.getFullName();
                String value3 = userOrder.getQuestion();
                try{
                    value3 = topicMapper.selectByPrimaryKey(userOrder.getTopicId()).getTopicName();
                }catch (Exception e){
                }
                for(int i = 0;i<3;i++){
                    Map<String,String> map = new HashMap<>();
                    if(i == 0){
                        map.put("value",value1);
                    }else if (i == 1){
                        map.put("value",value2);
                    }else{
                        map.put("value",value3);
                    }
                    maps.add(map);
                }
                if(userWechat != null){
                    wechatMiniUtil.sendTemplate(accessToken,"恭喜，导师已接受您的咨询预约！",userWechat.getPlatform(),maps,
                            "现在你可以进入订单详情页与导师私信聊天啦！",userOrder.getId(),"uxEAjSnPqNtAOsFBCZVsGAWs1gedv166LvJM4jX--2w");
                }
                if(userWechat1 != null){
                    wechatMiniUtil.sendTemplate(accessToken,"您已接受学员"+user.getFullName()+"的咨询预约",
                            userWechat1.getPlatform(),maps,"现在可以进入订单详情页私信学员啦，记得在约谈结束后点击“ 确认见面” 哦～",userOrder.getId(),"uxEAjSnPqNtAOsFBCZVsGAWs1gedv166LvJM4jX--2w");
                }

            }
            return RestBean.buildSuccess("导师接单成功");
        }else{
            return RestBean.build(RestBean.not_authorized,"当前订单无法进行此操作");
        }
    }
    /**
     * 导师拒绝订单
     * */
    public RestBean<?> teacherCancelOrder(int userOrderId,String openid){
        UserOrder userOrder = userPayOrderService.selectUserOrderById(userOrderId);
        UserOrderFlow userOrderFlow = userPayOrderService.selectUserOrderFlowByUserOrderId(userOrder.getId());
        int price = new Double(userOrder.getPrice()*100).intValue();
        Integer toUserId = userOrder.getToUserId();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(toUserId);
        List<TUser> users = user_service.selectByUserIds(ids);
        if(users == null || users.isEmpty()){
            return RestBean.build(RestBean.not_authorized,"当前人员无法进行此操作");
        }
        if(!users.get(0).getOpenid().equals(openid)){
            return RestBean.build(RestBean.not_authorized,"当前人员无法进行此操作");
        }

        if(userOrder.getStatus() == 2){
            List<Integer> userids = new ArrayList<Integer>();
            userids.add(userOrder.getUserId());
            List<TUser> tUsers = user_service.selectByUserIds(userids);
            if(tUsers != null && !tUsers.isEmpty()){
                UserWechat userWechat = userWechat_service.selectByMiniOpenid(tUsers.get(0).getOpenid());
                //	77AzhpkDHOQ3DcGpB4DG2pwQ5eU9Mrb-9-_6Vf5BaQY
                String accessToken = (String) servletContext.getAttribute("wechatAccessToken");
                List<Map<String,String>> list = new LinkedList<>();
                Map<String,String> map1 = new HashMap<>();
                try{
                    map1.put("value",topicMapper.selectByPrimaryKey(userOrder.getTopicId()).getTopicName());
                    list.add(map1);
                }catch (Exception e){
                    map1.put("value",userOrder.getQuestion());
                    list.add(map1);
                }
                map1 = new HashMap<>();
                map1.put("value", DateFormatUtil.dateToString(new Date()));
                list.add(map1);
                if(userWechat != null){
                    wechatMiniUtil.sendTemplate(accessToken,"您的咨询申请已被拒绝，不要灰心，快试试其他导师吧～",userWechat.getPlatform(),list,
                            "您的订单支付金额将在1个工作日内全款原路退回。",userOrder.getId(),"77AzhpkDHOQ3DcGpB4DG2pwQ5eU9Mrb-9-_6Vf5BaQY");
                }
            }
            userOrderFlowService.payRefund(userOrderFlow.getWechatTradeNo(),price,price,refundNotifyUrl,"导师拒绝订单，全额退款");
            return RestBean.buildSuccess("导师拒绝订单，退款中...");
        }else{
            return RestBean.build(RestBean.not_authorized,"当前订单无法进行此操作");
        }
    }
    /**
     * 导师确认 已交易
     * */
    public RestBean<?> teacherConfirmOrder(int userOrderId){
        UserOrder userOrder = userPayOrderService.selectUserOrderById(userOrderId);
        if(userOrder.getStatus() == 4){
            userOrder.setStatus(5);
            userPayOrderService.updateOrder(userOrder);
            int topicId = userOrder.getTopicId();
            topicMapper.addDealNum(topicId);
            tutorInfoMapper.addHelpsNumByUserId(userOrder.getToUserId());//导师帮助人数 +1
            tutorInfoMapper.addTotalIncomeByUserId(userOrder.getToUserId(),userOrder.getPrice());
            String accessToken = (String) servletContext.getAttribute("wechatAccessToken");
            TUser user = tUserMapper.selectByPrimaryKey(userOrder.getUserId());
            UserWechat userWechat = userWechat_service.selectByMiniOpenid(user.getOpenid());
            List<Map<String,String>> list = new LinkedList<>();
            Map<String,String> map1 = new HashMap<>();
            try{
                map1.put("value",topicMapper.selectByPrimaryKey(userOrder.getTopicId()).getTopicName());
                list.add(map1);
            }catch (Exception e){
                map1.put("value",userOrder.getQuestion());
                list.add(map1);
            }
            map1 = new HashMap<>();
            map1.put("value", DateFormatUtil.dateToString(new Date()));
            list.add(map1);
            if(userWechat != null){
                wechatMiniUtil.sendTemplate(accessToken,"您的咨询话题订单已完成，现在可以评价导师啦！",userWechat.getPlatform(),list,
                        "如有疑问，请咨询知识鸭客服",userOrder.getId(),"NFY3JMM3W17DJu6BiHY6aivS17uU1_TpLh9h26N5fh8");
            }
            return RestBean.buildSuccess("导师约聊成功");
        }else{
            return RestBean.build(RestBean.not_authorized,"当前订单无法进行此操作");
        }
    }
    /**
     * 已交易 待评价
     * */
    public RestBean<?> waitEvalOrder(int userOrderId){
        UserOrder userOrder = userPayOrderService.selectUserOrderById(userOrderId);
        if(userOrder.getStatus() == 5){
            userOrder.setStatus(8);
            userPayOrderService.updateOrder(userOrder);//

            return RestBean.buildSuccess("确认成功，等待用户评价");
        }else{
            return RestBean.build(RestBean.not_authorized,"当前订单无法进行此操作");
        }
    }

    /***
     * 用户取消订单，退款
     * */
    public RestBean<?> userCancelOrder(int userOrderId){
        UserOrder userOrder = userPayOrderService.selectUserOrderById(userOrderId);
        UserOrderFlow userOrderFlow = userPayOrderService.selectUserOrderFlowByUserOrderId(userOrder.getId());
        int price = new Double(userOrder.getPrice()*100).intValue();
        //D2Yz55W23Ih57Z3COqpRkzKnb3JWoUhtziKJMLHhtbA
        String accessToken = (String) servletContext.getAttribute("wechatAccessToken");
        TUser user = tUserMapper.selectByPrimaryKey(userOrder.getUserId());
        UserWechat userWechat = userWechat_service.selectByMiniOpenid(user.getOpenid());
        List<Map<String,String>> list = new LinkedList<>();
        Map<String,String> map1 = new HashMap<>();
        try{
            map1.put("value",topicMapper.selectByPrimaryKey(userOrder.getTopicId()).getTopicName());
            list.add(map1);
        }catch (Exception e){
            map1.put("value",userOrder.getQuestion());
            list.add(map1);
        }
        map1 = new HashMap<>();
        map1.put("value", "已取消");
        list.add(map1);
        wechatMiniUtil.sendTemplate(accessToken,"导师您好，您有学员取消了订单",userWechat.getPlatform(),list,"导师未接受订单前，学员可免费取消订单；如导师已接受订单，学员此时申请取消订单，我们将赔付您订单金额15%费用，7个工作日内到账。",userOrder.getId(),"D2Yz55W23Ih57Z3COqpRkzKnb3JWoUhtziKJMLHhtbA");
        if(userOrder.getStatus() == UserOrderStatusEnum.ACCEPT.getState()){
            //这里要扣手续费
            SettleParam settleParam = settleParam_service.selectSettleParamById(RefundTypeEnum.USER_BREAKRULE_FINE_PERCENTAGE.getState());
            double percent = (100.00 - 30.00) * 1.0 / 100.00;
            int refundFee = new Double(price * percent).intValue();
            System.out.println("refundFee ===========================>" + refundFee);
            System.out.println("price * percent ===========================>" + price * percent );
            userOrderFlowService.payRefund(userOrderFlow.getWechatTradeNo(),price,refundFee,refundNotifyUrl,"导师已确认，用户取消订单，扣除"+settleParam.getPercent()+"%手续费");
            return RestBean.buildSuccess("退款中，请稍后");
        }else if(userOrder.getStatus() == UserOrderStatusEnum.PAID.getState()){
            //这里不用扣手续费
            userOrderFlowService.payRefund(userOrderFlow.getWechatTradeNo(),price,price,refundNotifyUrl,"用户取消订单，全额退款");
            return RestBean.buildSuccess("退款中，请稍后");
        }else{
            //这里返回不能取消订单
            return RestBean.build(RestBean.not_authorized,"当前订单无法进行此操作");
        }
    }


    /**
     * 更新订单
     * */
    public RestBean<?> updateUserOrderById(UserOrder userOrder){
        if(userOrder == null || userOrder.getUserId() <= 0){
            return RestBean.buildError("无效用户订单");
        }else{
            if(userOrder.getStatus() == 1){
                userPayOrderService.updateByPrimaryKeySelective(userOrder);
            }else{
                return RestBean.buildError("该订单不能修改");
            }

        }
        return RestBean.buildSuccess("订单更新成功");
    }


    public RestBean<?> getUserOrderStatusByOrderId(int userOrderId,int status){
        return RestBean.buildSuccess(userPayOrderService.getUserOrderStatusByOrderId(userOrderId, status));
    }
}
